package simpleTaskBoard.dao;

import java.util.List;

import simpleTaskBoard.entities.TaskEntity;
import ch.ivyteam.ivy.environment.Ivy;
import ch.ivyteam.ivy.process.data.persistence.IIvyEntityManager;

public class TaskDAO {
	
	private static final String FIND_ALL_TASK_ENTITY = "SELECT t FROM TaskEntity t ORDER BY t.id";
	private static final String FIND_ALL_TASK_ENTITY_ASSIGNED_TO_USER = "SELECT t FROM TaskEntity t WHERE t.assigned = :userName ORDER BY t.id";
	
	private IIvyEntityManager ivyEm;
	public TaskDAO(){
		
		ivyEm = Ivy.persistence().get("PersistenceTask");
	}
	
	public void addTask(TaskEntity task){
		ivyEm.persist(task);
	}
	
	public void updateTask(TaskEntity task){
		ivyEm.merge(task);
	}
	
	@SuppressWarnings("unchecked")
	public List<TaskEntity> getAll(){
		List<TaskEntity> result = (List<TaskEntity>) ivyEm.createQuery(FIND_ALL_TASK_ENTITY).getResultList();
		return result;
	}
	
	public TaskEntity getByID(long id){
		TaskEntity result =ivyEm.find(TaskEntity.class, id);
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<TaskEntity> findAllTaskAssignedToUser(String userName) {
		List<TaskEntity> result = (List<TaskEntity>) ivyEm.createQuery(FIND_ALL_TASK_ENTITY_ASSIGNED_TO_USER)
															.setParameter("userName", userName).getResultList();
		return result;
	}
}
